package com.peihua.controller;

import com.peihua.domain.Addresses;
import com.peihua.domain.Result;
import com.peihua.service.AddressesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressesService addressesService;

    @GetMapping("/list")
    public Result list(){
        List<Addresses> list = addressesService.list();
        return Result.success(list);
    }

    @GetMapping("/get/{id}")
    public Result get(@PathVariable Integer id){
        Addresses one = addressesService.getById(id);
        if(one == null){
            return Result.error(404L, "地址不存在");
        }
        return Result.success(one);
    }

    @PostMapping("/saveAddress")
    public Result save(@RequestBody Addresses addr){
        if(Objects.isNull(addr)){
            return Result.error(400L, "请求体不能为空");
        }
        if(!StringUtils.hasText(addr.getRecipientName())){
            return Result.error(400L, "收货人必填");
        }
        if(!StringUtils.hasText(addr.getPhoneNumber())){
            return Result.error(400L, "手机号必填");
        }
        if(!StringUtils.hasText(addr.getAddressLine1())){
            return Result.error(400L, "收货地址必填");
        }
        if(addr.getIsDefault() == null){
            addr.setIsDefault(0);
        }
        boolean ok = addressesService.save(addr);
        return ok ? Result.success() : Result.error(500L, "保存失败");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Addresses addr){
        if(addr == null || addr.getAddressId() == null){
            return Result.error(400L, "缺少地址ID");
        }
        boolean ok = addressesService.updateById(addr);
        return ok ? Result.success("修改成功") : Result.error(500L, "修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        boolean ok = addressesService.removeById(id);
        return ok ? Result.success() : Result.error(500L, "删除失败");
    }
}
